<?php

$url = $_POST['url'];
if (!$url) {
    eexit(json_encode(['code' => 100, 'msg' => '请输入链接']));
}
// 判断链接规则
$pattern = '/^(?:([A-Za-z]+):)?(\/{0,3})([0-9.\-A-Za-z]+)(?::(\d+))?(?:\/([^?#]*))?(?:\?([^#]*))?(?:#(.*))?$/';
$result  = preg_match($pattern, $url);
if (!$result) {
    exit(json_encode(['code' => 100, 'msg' => '请输入正确规则的链接']));
}

require_once './config.php';
require_once './redis.php';

//生成，写入并返回
$code = createStr();
//写入缓存
redis()->set($prefix . $code, $url);
redis()->rpush($cacheName, $prefix . $code);
exit(json_encode(['code' => 200, 'msg' => '生成成功', 'data' => $host . $code]));

/**
 * 生成字符串
 * @return string
 */
function createStr(): string
{
    $data = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];
    $info = array_rand($data, 6);
    $res  = '';
    foreach ($info as $k => $v) {
        $res .= $data[$v];
    }
    $code = redis()->get($res);
    if ($code) {
        return createStr();
    } else {
        return $res;
    }
}